//
//  UserDefaultGroup.swift
//  WidgetExample
//
//  Created by Ben on 2022/4/17.
//  Copyright © 2022 Ben. All rights reserved.
//

import Foundation

let APP_GROUP_IDENTIFER = "group.Ben.widget"


class UserDefaultGroup {
    static let shared = UserDefaultGroup()
    
    private let userDefaults = UserDefaults(suiteName: APP_GROUP_IDENTIFER)
    
    
    var timeWidgetShowWeek: Bool {
        set {
            userDefaults?.set(newValue, forKey: "TIME_WIDGET_SHOW_WEEK")
        }
        get {
            if let value = userDefaults?.value(forKey: "TIME_WIDGET_SHOW_WEEK") as? Bool {
                return value
            } else {
                return true
            }
        }
    }
    
    var timeWidgetTypeList: [TimeWidgetTypeModel] {
        set {
            
            var jsonData: Data? = nil
            guard let jsonData = try? JSONEncoder().encode(newValue) else {
                return
            }
            userDefaults?.set(jsonData, forKey: "TIME_WIDGET_TYPE_LIST")
//            userDefaults?.synchronize()
        }
        get {
            guard let jsonData = userDefaults?.value(forKey: "TIME_WIDGET_TYPE_LIST") as? Data else {
                return [.normal]
            }
            
            do {
                let models = try JSONDecoder().decode([TimeWidgetTypeModel].self, from: jsonData)
                
                return models
            } catch {
                print(error)
                return [.normal]
            }
        }
    }
    
    func timeWidgetStyle(with Id: String) -> TimeWidgetTypeModel? {
        return timeWidgetTypeList.first(where: { (typeModel) -> Bool in
            return typeModel.id == Id
        })
    }
}
